import os
import tarfile
import getpass
import paramiko
import sys

# --- CONFIGURATION ---
# EXACT Local Path
LOCAL_SOURCE = "/TOP/GitHub/FurryOS"

# EXACT Remote Path
REMOTE_DEST = "/home/anthro/FurryOS/sourcecode"

# Connection Details
HOST = "50.28.69.47"
USER = "anthro"
PORT = 22

# EXCLUSION LIST (Crucial for speed)
# This ignores all the heavy build folders and temporary junk.
EXCLUDES = [
    # Live-Build Artifacts (Heavy!)
    'chroot', 'binary', 'cache', '.build', 'FurryOS-Builds',
    # Version Control
    '.git', '.gitignore',
    # Large Binaries/Archives
    '*.iso', '*.img', '*.squashfs', '*.tar.gz', '*.zip',
    # IDE/System Junk
    '.vscode', '.idea', '__pycache__', '*.swp', '*.DS_Store',
    # Logs
    '*.log'
]

def filter_tar(tarinfo):
    """Smart filter to keep source code but drop the heavy build junk."""
    fname = tarinfo.name
    
    for exclude in EXCLUDES:
        # Check extensions (e.g., *.iso)
        if exclude.startswith('*'):
            if fname.endswith(exclude[1:]): return None
        # Check directories (e.g., /chroot)
        elif f"/{exclude}" in fname or fname.endswith(f"/{exclude}") or fname == exclude:
            return None
            
    return tarinfo

def create_archive(source_dir, output_filename):
    print(f"📦 Compressing Source Code...")
    print(f"   Source: {source_dir}")
    print(f"   (Excluding: chroot, binary, cache, .git, ISOs...)")
    
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir), filter=filter_tar)
    
    size_mb = os.path.getsize(output_filename) / (1024 * 1024)
    print(f"✅ Clean Archive Created: {output_filename} ({size_mb:.2f} MB)")

def deploy_to_server(archive_name, password):
    print(f"\n🚀 Connecting to {HOST}...")
    
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, port=PORT, username=USER, password=password)
        sftp = ssh.open_sftp()
        
        # 1. Upload Archive
        remote_tmp = f"/tmp/{archive_name}"
        print(f"📤 Uploading payload...")
        sftp.put(archive_name, remote_tmp)
        print("   Upload complete.")
        
        # 2. Prepare Remote Folder (Clean slate)
        print(f"📂 Setting up: {REMOTE_DEST}")
        # Delete old source folder to ensure no ghost files remain
        ssh.exec_command(f"rm -rf {REMOTE_DEST}")
        ssh.exec_command(f"mkdir -p {REMOTE_DEST}")
        
        # 3. Extract
        print("📦 Extracting on server...")
        # strip-components=1 removes the parent folder name so contents go DIRECTLY into sourcecode
        stdin, stdout, stderr = ssh.exec_command(f"tar -xzf {remote_tmp} -C {REMOTE_DEST} --strip-components=1")
        
        if stdout.channel.recv_exit_status() == 0:
            print("✅ Extraction Successful.")
        else:
            print(f"❌ Extraction Error: {stderr.read().decode()}")
            
        # 4. Make scripts executable
        ssh.exec_command(f"chmod +x {REMOTE_DEST}/*.sh")
        
        # 5. Cleanup
        sftp.remove(remote_tmp)
        sftp.close()
        ssh.close()
        return True

    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        return False

def main():
    archive_name = "furryos_source_deploy.tar.gz"
    
    if not os.path.exists(LOCAL_SOURCE):
        print(f"❌ Error: Local path not found: {LOCAL_SOURCE}")
        return

    # Get Password
    print(f"Deploying to {USER}@{HOST}")
    pwd = getpass.getpass("🔑 Enter SSH Password: ")
    
    # Run Steps
    create_archive(LOCAL_SOURCE, archive_name)
    if deploy_to_server(archive_name, pwd):
        print("\n" + "="*40)
        print("✨ DEPLOYMENT SUCCESSFUL ✨")
        print("="*40)
        print("You can now build on the VPS:")
        print(f"1. ssh {USER}@{HOST}")
        print(f"2. cd {REMOTE_DEST}")
        print("3. sudo ./build4.sh")
    
    # Clean local file
    if os.path.exists(archive_name):
        os.remove(archive_name)

if __name__ == "__main__":
    main()
